package chapter17;

import java.util.Objects;
import java.util.WeakHashMap;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/24 17:16
 */
class Element {
    private String ident;

    public Element(String ident) {
        this.ident = ident;
    }

    @Override
    public String toString() {
        return ident;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o instanceof Element) {
            return false;
        }
        Element element = (Element) o;
        return Objects.equals(ident, element.ident);
    }

    @Override
    public int hashCode() {
        return Objects.hash(ident);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalizing " + getClass().getSimpleName() + " " + ident);
    }
}

class Key extends Element {

    public Key(String id) {
        super(id);
    }
}

class Value extends Element {

    public Value(String ident) {
        super(ident);
    }
}

public class CanonicalMapping {
    public static void main(String[] args) {
        int size = 1000;
        Key[] keys = new Key[size];
        WeakHashMap<Key, Value> map = new WeakHashMap<>();
        for (int i = 0; i < size; i++) {
            Key key = new Key(Integer.toString(i));
            Value value = new Value(Integer.toString(i));
            //每三个将一个普通引用放入到数组中（强引用）
            //这些引用不会被垃圾回收
            if (i % 3 == 0) {
                keys[i] = key;
            }
            map.put(key, value);
        }
        System.gc();
    }
}
